// useScroll.js

import  {debounce}  from "./debounce.js"

export default function useScroll(elRef) {
  let el = window
  const isReachBottom = ref(false)
  const clientHeight = ref(0)
  const scrollTop = ref(0)
  const scrollHeight = ref(0)

  const scrollListenerHandler = debounce(() => {
    if (el === window) {
      clientHeight.value = document.documentElement.clientHeight || document.body.clientHeight
      scrollHeight.value = document.documentElement.scrollHeight || document.body.scrollHeight
      scrollTop.value = document.documentElement.scrollTop || document.body.scrollTop
    } else {
      clientHeight.value = el.clientHeight
      scrollTop.value = el.scrollTop
      scrollHeight.value = el.scrollHeight
    }
    if (clientHeight.value + scrollTop.value >= scrollHeight.value) {
      isReachBottom.value = true
    } else {
      isReachBottom.value = false
    }
    console.log('#########scrollTop', scrollTop.value)
    console.log('#########clientHeight', clientHeight.value)
    console.log('#########scrollHeight', scrollHeight.value)
    console.log('#########isReachBottom', isReachBottom.value)
  }, 100)
  onMounted(() => {
    if (elRef) {
      el = elRef.value
    }
    el.addEventListener('scroll', scrollListenerHandler)
  })
  onUnmounted(() => {
    el.removeEventListener('scroll', scrollListenerHandler)
  })

  return { isReachBottom, clientHeight, scrollTop, scrollHeight }
}